//
//  PhotoBrowerCell.m
//  SinaWebo
//
//  Created by wwj on 16/6/21.
//  Copyright © 2016年 亦心. All rights reserved.
//

#import "PhotoBrowerCell.h"
#import "FWProgressRingView.h"
#import <UIImageView+WebCache.h>
#import "FWGroupModel.h"

@interface PhotoBrowerCell ()<UIScrollViewDelegate, UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollerView;
@property (weak, nonatomic) UIImageView *imageView;
@property (weak, nonatomic) IBOutlet FWProgressRingView *progressView;

@property (assign, nonatomic) CGPoint beginPoint;
@end

@implementation PhotoBrowerCell

- (UIImageView *)imageView{
    if (_imageView == nil) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.frame = CGRectZero;
        imageView.userInteractionEnabled = YES;
        [self.scrollerView addSubview:imageView];
        _imageView = imageView;
    }
    return _imageView;
}

- (void)setModel:(FWGroupModel *)model{
    _model = model;
    [self resetView];
    
    [self.progressView setProgress:model.progress animated:YES];
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:model.url] placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        CGFloat progress = 1.0 * receivedSize / expectedSize;
        [self.progressView setProgress:progress animated:YES];
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        self.progressView.hidden = YES;
        
        CGFloat picW = self.width;
        CGFloat picH = self.width / image.size.width * image.size.height;
        self.imageView.size = CGSizeMake(picW, picH);
        if (picH > self.height) {
            self.scrollerView.contentSize = CGSizeMake(0, picH);
        }else{
            
            self.imageView.center = CGPointMake(kScreenW * 0.5, kScreenH * 0.5);
        }
    }];
    
    [self bringSubviewToFront:self.progressView];
    if (self.imageView.image) {
        self.progressView.hidden = YES;
    }else{
        self.progressView.hidden = NO;
    }
    
    if (_model.isAnimtion) {
        [self startAnimtion:_model.fromView];
    }
    
}

- (void)startAnimtion:(UIView *)view{
    CGRect frame = [view convertRect:_model.fromView.bounds toView:self];
    
    CGRect formFrame = view.frame;
    formFrame.origin.y = frame.origin.y;
    if (frame.origin.x > 0) {
        formFrame.origin.x = frame.origin.x;
    }
    CGRect toFrame = self.imageView.frame;
    self.imageView.frame = formFrame;
    self.superView.alpha = 0.4;
    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.imageView.frame = toFrame;
        self.superView.alpha = 1.0;
    } completion:^(BOOL finished) {
        _model.isAnimtion = FALSE;
    }];

}

- (void)hidden{
    CGRect frame = [_model.fromView convertRect:_model.fromView.bounds toView:self];
    [self resetView];
    CGRect toFrame = frame;
    toFrame.origin.x = frame.origin.x;
    toFrame.size = _model.fromView.size;
    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.imageView.frame = toFrame;
        self.superView.alpha = 0.8;
    } completion:^(BOOL finished) {
        [self removeSuperView];
    }];
    
}

- (void)removeSuperView{
    [self.superView removeFromSuperview];
    [UIApplication sharedApplication].statusBarHidden = NO;
}

- (void)awakeFromNib{
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidden)];
    [self addGestureRecognizer:tap];
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
    tap2.numberOfTapsRequired = 2;
    [tap requireGestureRecognizerToFail:tap2];
    [self addGestureRecognizer:tap2];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
    pan.delegate = self;
    [self addGestureRecognizer:pan];
    
    self.scrollerView.backgroundColor = [UIColor clearColor];
    self.scrollerView.delegate = self;
    self.scrollerView.maximumZoomScale = 3.0;
    self.scrollerView.multipleTouchEnabled = YES;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    CGPoint point = [gestureRecognizer locationInView:self.imageView];
    if (point.x > 220 || point.x < 150) {
        return NO;
    }
    return YES;
}

- (void)panGesture:(UIPanGestureRecognizer *)pan{
    CGPoint point = [pan locationInView:self];
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
            self.beginPoint = point;
            break;
            
        case UIGestureRecognizerStateChanged:{
            CGFloat deta = point.y - self.beginPoint.y;
            self.scrollerView.y = deta;
            CGFloat alpha = (900 - fabs(deta)) / 900;
            
            [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionCurveLinear animations:^{
                self.superView.alpha = alpha;
            } completion:nil];
        }
            break;
            
        case UIGestureRecognizerStateEnded:{
            CGFloat deta = point.y - self.beginPoint.y;
            
            MyLog(@"%f,%f", deta, point.y);
            if (fabs(deta) > 200) {
                BOOL moveToTop = deta < 0;
                [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                    if (moveToTop) {
                        self.scrollerView.y =  -self.scrollerView.height;
                    }else{
                        self.scrollerView.y = self.scrollerView.height;
                    }
                } completion:^(BOOL finished) {
                    [self removeSuperView];
                }];
            }else {
                [UIView animateWithDuration:0.3 animations:^{
                    self.superView.alpha = 1.0;
                    self.scrollerView.y = 0.0;
                }];
            }
        }
            break;
            
        case UIGestureRecognizerStateCancelled:
            MyLog(@"UIGestureRecognizerStateEnded");
            break;
            
        case UIGestureRecognizerStateFailed:
            MyLog(@"UIGestureRecognizerStateFailed");
            break;
            
        case UIGestureRecognizerStatePossible:
            MyLog(@"UIGestureRecognizerStatePossible");
            break;
            
    }
    
}



- (void)doubleTap:(UITapGestureRecognizer *)tap{
    if (self.scrollerView.zoomScale > 1.0) {
        [self.scrollerView setZoomScale:1.0 animated:YES];
    }else {
        CGPoint touchPoint = [tap locationInView:self.imageView];
        CGFloat newZoomScale = self.scrollerView.maximumZoomScale;
        CGFloat xsize = self.width / newZoomScale;
        CGFloat ysize = self.height / newZoomScale;
        [self.scrollerView zoomToRect:CGRectMake(touchPoint.x - xsize * 0.5, touchPoint.y - ysize * 0.5, xsize, ysize) animated:YES];
        
    }
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    UIView *subView = self.imageView;
    
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    
    subView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                 scrollView.contentSize.height * 0.5 + offsetY);
}

- (void)resetView{
    if (_model.scrollerView == nil) {
        self.scrollerView.contentSize = CGSizeZero;
        self.scrollerView.contentInset = UIEdgeInsetsZero;
        self.scrollerView.contentOffset = CGPointZero;
    }else{
        _scrollerView.frame = _model.viewF;
    }
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    _model.scrollerView = scrollView;
    _model.viewF = view.frame;
}

@end
